package com.clps.rulesregulations.controller;

import com.clps.rulesregulations.domain.*;
import com.clps.rulesregulations.service.*;
import com.clps.rulesregulations.util.Const;
import com.clps.rulesregulations.util.ResourceTree;
import com.clps.rulesregulations.util.ResultView;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制层
 *
 * @author zhangchao
 * @date 2018-10-08
 */
@Controller
@RequestMapping(value = "/resource")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;
    @Autowired
    private RegulationService regulationService;
    @Autowired
    private ShiroService shiroService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleResourceService roleResourceService;

    /**
     * 跳转到菜单展示页
     *
     * @return
     */
    @GetMapping("/list")
    public String toList() {
        return "manager/resource";
    }

    /**
     * 分页查询所有菜单
     *
     * @param condition
     * @return
     * @throws Exception
     */
    @PostMapping("/list")
    @ResponseBody
    public ResultView list(@RequestBody Map<String, Object> condition) throws Exception {

        ResultView resultView = new ResultView(ResultView.SUCCESS);
        PageInfo<Resource> users = resourceService.findResourcesByPage(condition);
        resultView.setValue(users);
        return resultView;
    }

    /**
     * 添加菜单
     *
     * @param resource
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public ResultView add(@RequestBody Resource resource) {

        ResultView resultView = new ResultView(ResultView.SUCCESS);
        if (StringUtils.isBlank(resource.getName()) || StringUtils.isBlank(String.valueOf(resource.getParentId()))) {
            resultView.setStatus(ResultView.ERROR);
            resultView.setMsg("请填入必填项");
            return resultView;
        }

        resource.setCanDel(Const.CANDEL);
        resourceService.addResource(resource);
        return resultView;
    }

    /**
     * 删除资源
     *
     * @param resourceId
     * @return
     */
    @CacheEvict(cacheNames = "resources", allEntries = true)
    @GetMapping("/delete")
    @ResponseBody
    public ResultView delResource(@RequestParam Integer resourceId) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        List<Resource> resourceList = resourceService.selectAll();
        List<String> delList = new ArrayList();
        delList.add(String.valueOf(resourceId));
        if (resourceList != null && resourceList.size() > 0) {
            for (int i = 0; i < resourceList.size(); i++) {
                Resource rs = resourceList.get(i);
                String fullUrl = rs.getFullUrl();
                if (fullUrl != null) {
                    String[] arr = fullUrl.split(",");
                    for (int k = 0; k < arr.length; k++) {
                        String value = arr[k];
                        if (resourceId == Integer.valueOf(value)) {
                            delList.add(String.valueOf(rs.getId()));

                            continue;
                        }
                    }
                }

            }
        }
        if (delList != null && delList.size() > 0) {
            String[] strings = new String[delList.size()];
            delList.toArray(strings);
            resourceService.deleteAll(strings);
        }

//        shiroService.updatePermission();
        return resultView;
    }

    /**
     * 根据资源ID查询资源内容
     *
     * @param resourceId
     * @return
     */
    @GetMapping("/edit")
    @ResponseBody
    public ResultView findResource(@RequestParam Integer resourceId) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        Resource resource = resourceService.findResourceById(resourceId);
        if (resource != null) {
            String fullUrl = resource.getFullUrl();
            if (!StringUtils.isEmpty(fullUrl)) {
                String[] arr = fullUrl.split(",");
                Integer[] iarr = new Integer[arr.length];
                for (int i = 0; i < arr.length; i++) {
                    iarr[i] = Integer.valueOf(arr[i]);
                }
                resource.setFullUrlArr(iarr);
            }
        }
        resultView.setValue(resource);
        return resultView;
    }

    /**
     * 修改资源
     *
     * @param resource
     * @return
     */
    @CacheEvict(cacheNames = "resources", allEntries = true)
    @PostMapping("/edit")
    @ResponseBody
    public ResultView editResource(@RequestBody Resource resource) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        String fullUrl = resource.getFullUrl();
        String[] arr = fullUrl.split(",");
        String parentId = arr[arr.length - 1];
        resource.setParentId(Integer.valueOf(parentId));
        resourceService.updateResource(resource);
//        shiroService.updatePermission();
        return resultView;
    }

    /**
     * 查询所有菜单
     *
     * @return
     */

    @GetMapping("/all")
    @ResponseBody
    public ResultView findAllMenu(Resource rs) {
        Subject currentUser = SecurityUtils.getSubject();
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        Map<String, Object> map = new HashMap<String, Object>();
        if (currentUser.hasRole("管理员")) {
            List<ResourceTree> menuDbs = resourceService.findAllAsTree();
            if (menuDbs.size() > 0) {
                List<ResourceTree> menus = menuDbs.get(0).getChildren();
                for (int i = 0; i < menuDbs.size(); i++) {
                    ResourceTree rt = menuDbs.get(i);
                    rt.setShow(true);
                }
                map.put("menus", menus);
                map.put("allMenus", menuDbs);
            }
        } else {
            Session session = SecurityUtils.getSubject().getSession();
            User u = (User) session.getAttribute("userSession");
            //查询该角色所有资源ID
            List<Role> roles = roleService.findRolesByUserId(u.getId());
            List<Integer> resourceIds = new ArrayList<>();
            if (roles != null && roles.size() > 0) {
                Role role = roles.get(0);
                resourceIds = roleResourceService.findResourceIdsByRoleId(role.getId());
            }

            List<ResourceTree> menuDbs = resourceService.findAllAsTree();
            if (menuDbs.size() > 0) {
                List<ResourceTree> menus = menuDbs.get(0).getChildren();

                for (int i = 0; i < menuDbs.size(); i++) {
                    boolean bool = false;
                    ResourceTree rt = menuDbs.get(i);
                    if (resourceIds != null) {
                        for (int m = 0; m < resourceIds.size(); m++) {
                            int ids = resourceIds.get(m);
                            if (ids == rt.getId()) {
                                bool = true;
                                break;
                            }

                            Resource resource = resourceService.findResourceById(ids);
                            String fullUrl = resource.getFullUrl();

                            if (!StringUtils.isEmpty(fullUrl)) {
                                String[] arr = fullUrl.split(",");
                                for (int k = 0; k < arr.length; k++) {
                                    if (rt.getId() == Integer.valueOf(arr[k])) {
                                        bool = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    rt.setDisabled(bool);
                }
                map.put("menus", menus);
                map.put("allMenus", menuDbs);
            }
        }
        List<ResourceTree> regularMenuDbs = regulationService.findMenuTree();
        if (regularMenuDbs != null && regularMenuDbs.size() > 0) {
            if (regularMenuDbs.get(0).getChildren() != null && regularMenuDbs.get(0).getChildren().size() > 0) {
                map.put("regulationMenus", regularMenuDbs.get(0).getChildren().get(0).getChildren());
            }
        }

        List<ResourceTree> deptTrees = regulationService.findDeptTrees();
        if (deptTrees != null && deptTrees.size() > 0) {
            if (deptTrees.get(0).getChildren() != null && deptTrees.get(0).getChildren().size() > 0) {
                map.put("deptTrees", deptTrees.get(0).getChildren());
            }
        }

        String index = "";
        if (rs != null) {
            String url = rs.getUrl();
            Integer type = rs.getType();
            if (type == 1) {
                if ("/".equals(url)) {
                    index = "-1";
                } else if ("/regulation/search".equals(url)) {
                    index = "-1";
                } else {
                    Resource rl = resourceService.findResourceByUrl(url);
                    if (rl != null) {
                        index = rl.getFullUrl().replaceAll(",", "-") + "-" + String.valueOf(rl.getId());
                        index = index.substring(2, index.length());
                    }
                }

            } else {
                if (!StringUtils.isEmpty(url)) {
                    Rule rule = regulationService.selectRule(url);
                    if (rule != null) {
                        Session session = SecurityUtils.getSubject().getSession();
                        String regulation = (String) session.getAttribute("regulation");
                        String keywordid = (String) session.getAttribute("keywordid");
                        if (StringUtils.isEmpty(regulation)) {
                            regulation = "9999";
                        }
                        try {
                            if (rule.getParentId() == 1) {
                                index = rule.getFullPath().replaceAll("/", "-");
                                index = regulation + "-" + String.valueOf(rule.getCatalogId());
                            } else {
                                index = rule.getFullPath().replaceAll("/", "-");
                                index = regulation + index.substring(2, index.length()) + rule.getParentId() + "-" + String.valueOf(rule.getCatalogId());
                            }

                        } catch (Exception e) {

                        }

                        if ("8888".equals(regulation)) {
                            index = keywordid;
                        }
                    }
                }
            }
        }


        if (currentUser.hasRole("管理员")) {
            if(StringUtils.isEmpty(index)){
                index="1";
            }
        } else {
            if(StringUtils.isEmpty(index)){
                index="-1";
            }
        }

        map.put("defaultIndex", index);

        resultView.setValue(map);
        return resultView;
    }
}
